package com.hc.comm.servlet;


import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.DispatcherServlet;

import com.hc.comm.base.OperateResultModel;
import com.hc.comm.exception.OperateException;
import com.hc.comm.utils.Constant.HttpScopeEnum;
import com.hc.comm.utils.Constant.ResultEnum;
import com.hc.comm.utils.FrameUtil;
import com.hc.comm.utils.ServletUtil;
import com.hc.comm.utils.StringUtil;



public class DispatcherServletWrap extends DispatcherServlet {
	private static Logger logger = Logger
			.getLogger(DispatcherServletWrap.class);
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	/**
	 * 操作异常提示页面
	 */
	private String operateExceptionUrl = "/WEB-INF/jsp/index.jsp";

	/**
	 * 登入页面
	 */
	private String loginUrl = "/WEB-INF/login.jsp";

	/**
	 * 404页面
	 */
	private String page404 = "";

	@Override
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		operateExceptionUrl = config.getInitParameter("operateExceptionUrl");
		String loginUrlTemp = config.getInitParameter("loginUrl");
		page404 = config.getInitParameter("page404");
		if (StringUtil.isNotEmpty(loginUrlTemp)) {
			this.loginUrl = loginUrlTemp;
		}
	}

	@Override
	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// System.out.println(request.getRequestURL());
		inService(request, response);
	}

	protected void inService(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		HttpServletRequest processedRequest = request;
		processedRequest = this.checkMultipart(request);
		request = processedRequest != request ? processedRequest : request;
		// 判断是否是ajax请求
		boolean isAjaxRequest = ServletUtil.isAjaxRequest(request);
		try {
			super.service(request, response);
		} catch (Exception e) {
			if (isAjaxRequest) {
				// ajax异常处理
				OperateResultModel resultModel = OperateResultModel
						.createOperateResultModel();
				if (e.getCause() instanceof OperateException) {
					logger.error(e.getMessage());
					OperateException oe = (OperateException) e.getCause();
					resultModel
							.setResultState(oe.getResultState() == null ? ResultEnum.INFO
									.getResult() : oe.getResultState());
					resultModel.setFeedBackInfo(oe.getMessage());
				} else {
					logger.error(e.getMessage(), e);
					ByteArrayOutputStream stream = new ByteArrayOutputStream();
					PrintStream ps = new PrintStream(stream);
					e.printStackTrace(ps);
					resultModel.setResultState(ResultEnum.ERROR.getResult());
					resultModel.setFeedBackInfo(FrameUtil
							.getResource("sysEx.00001"));

				}
				ServletUtil.outputJsonMessage(request, response, resultModel);
			} else {
				// 非ajax异常处理
				OperateException e1 = null;
				if (e instanceof OperateException) {
					e1 = (OperateException) e;
				} else if (e.getCause() instanceof OperateException) {
					e1 = (OperateException) e.getCause();
				}
				if (e1 != null) {
					logger.error(e.getMessage());
					if (ResultEnum.NOLOGIN.getResult().endsWith(
							e1.getResultState())) {
						if (loginUrl.startsWith(request.getContextPath())) {
							response.sendRedirect(loginUrl);
						} else {
							response.sendRedirect(request.getContextPath()
									+ loginUrl);
						}
						return;
					} else if (ResultEnum.NOTFINDPAGE.getResult().equals(
							e1.getResultState())) {
						response.setStatus(HttpServletResponse.SC_NOT_FOUND);
						request.getRequestDispatcher(page404).forward(request,
								response);
					} else {
						ServletUtil.putValueToScope(request, response,
								ServletUtil.OPERATEEXCEPTIONINFO_REQUEST,
								e1.getMessage(), HttpScopeEnum.REQUEST);
						ServletUtil.putValueToScope(request, response,
								"oprReturnurl", e1.getReturnUrl(),
								HttpScopeEnum.REQUEST);
						// 跳转到操作错误页面(OperateException异常有对应的视图界面)
						request.getRequestDispatcher(operateExceptionUrl)
								.forward(request, response);
					}
				} else {
					logger.error(e.getMessage(), e);
					ServletUtil.putValueToScope(request, response,
							ServletUtil.OPERATEEXCEPTIONINFO_REQUEST,
							FrameUtil.getResource("sysEx.00001"),
							HttpScopeEnum.REQUEST);
					request.getRequestDispatcher(operateExceptionUrl).forward(
							request, response);
				}
			}

		}
	}

}
